//index.js
//获取应用实例
const app = getApp()
const util = require("../../utils/util.js")

Page({
  data: {
    swiperbox: app.globalData.swiperbox,
    swiper: app.globalData.swiper,

    userInfo:{},
    hasUserInfo: false,
    // canIUse: wx.canIUse('button.open-type.getUserInfo'),
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    isHide: false,
    islogin: false,

    grid:[
      {
        id:0,
        url: 'proxyCenter/proxyCenter',
        icon:'icon-ziyuan',
        txt:'代理中心',
        tap:'gridNavigateUrl',
      },{
        id: 1,
        url: 'merchantCenter/merchantCenter',
        icon: 'icon-shangjia',
        txt: '商家中心',
        tap: 'gridNavigateUrl',
      },{
        id: 2,
        url: 'userCenter/userCenter',
        icon: 'icon-yonghu',
        txt: '用户中心',
        tap: 'gridNavigateUrl',
      }, {
        id: 3,
        url: 'proxyApply/proxyApply',
        icon: 'icon-wj-rysq',
        txt: '申请代理',
        tap: 'gridNavigateUrl',
      }, {
        id: 4,
        url: 'merchantApply/merchantApply',
        icon: 'icon-shenqingjiaru',
        txt: '申请商家',
        tap: 'gridNavigateUrl',
      }, {
        id: 5,
        url: 'serviceCenter/serviceCenter',
        icon: 'icon-weixiu',
        txt: '安装维修',
        tap: 'gridNavigateUrl',
      }
    ]
  },
  modal:function(mess){
    wx.showModal({
      title: '提示',
      content: mess,
    })
  },
  onLoad: function (options) {
    this.timer = setTimeout(() => {
      this.getUserInfo();
      this.setData({
        swiper: wx.getStorageSync('swiper') || app.globalData.swiper
      })
      this.identityType();
      wx.stopPullDownRefresh();
    }, 500)
  },
  bossIndex:function(){
    // || this.data.userInfo.openid == 'oSMQR5caRr7MDB31mKADreLOt8Ik'
    if (this.data.userInfo.openid == 'oSMQR5QUdgu-_HW2T1wcWQes4T2U' || this.data.userInfo.openid == 'oSMQR5caRr7MDB31mKADreLOt8Ik' || this.data.userInfo.openid == 'oSMQR5XeFM0_5oly4958wpHB1FQE'){
      wx.navigateTo({
        url: '../../pages/boss/index/index',
      })
    }
  },
  getUserInfo: function () {
    var that = this;
    if (app.globalData.userInfo) {
      that.setData({
        islogin: true,
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
      app.globalData.islogin = true;
    } else {}
  },
  login:function(){
    // 登录  如没有则调用wxLogin获取code
    wx.login({
      success: function (res) {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        if (res.code) {
          console.log(res.code)
          // 用户授权登录
          wx.request({
            url: util.getUrl() + 'identity/login',
            method: 'POST',
            header: {
              'content-type': 'application/x-www-form-urlencoded'
            },
            data: { 'code': res.code },
            success: function (res) {
              console.info("login.success", res)
              if (res.data.code == 200) {
                app.globalData.openId = res.data.data.openid;
                app.globalData.userInfo = res.data.data.customer;
                wx.setStorageSync('userInfo', res.data.data.customer);
                app.globalData.swiper = res.data.data.advertising;
                wx.setStorageSync('swiper', res.data.data.advertising);
                that.setData({
                  islogin: true,
                  userInfo: res.data.data.customer,
                  hasUserInfo: true
                });
                app.globalData.islogin = true;
              } else if (res.data.code == 401) {
                console.log("401")
                app.globalData.openId = res.data.data.openid;
                // 用户没有授权
                // 改变 isHide 的值，显示授权页面
                wx.showModal({
                  title: '提示',
                  content: '您还未进行登录，小程序内的某些功能将无法正常使用，请问是否去登录？',
                  success(res) {
                    if (res.confirm) {
                      that.setData({
                        isHide: true
                      });
                    } else if (res.cancel) {
                      that.setData({
                        islogin: false
                      });
                      app.globalData.islogin = false;
                    }
                  }
                })
              }
            }, fail: function (res) {
              console.info("login.fail:", res)
            }, complete: function (res) {
              console.info("login.complete:", res)
            }
          })
        }
      }, fail: function (err) {
        console.log('wx.login 接口调用失败，将无法正常使用开放接口等服务', err)
      }, complete: function () {
        console.info("wx.login:complete")
      }
    })
  },
  // 用户类型权限
  identityType:function(){
    var that = this;
    this.setData({
      swiper: wx.getStorageSync('swiper') || app.globalData.swiper,
    })
    if (app.globalData.islogin == true) {
      var type = that.data.userInfo.type || 'customer';
      /*
       customer 用户：[234]可进，[015]去提示页
       agent 代理：[012345]可进
       shop 商家：[1234]可进，[05]提示页
       engineer 维护,salesman 业务人员：[25]可进，[0134]提示框（你是维护人员、业务人员，还不能申请代理，商家）
      */
      if (type == 'customer') {
        that.setData({
          ["grid[0].tap"]: 'gridNavigateUrl',
          ["grid[0].url"]: 'identityTip/identityTip?type=agent',
          ["grid[1].tap"]: 'gridNavigateUrl',
          ["grid[1].url"]: 'identityTip/identityTip?type=merchant',
          ["grid[5].tap"]: 'gridNavigateUrl',
          ["grid[5].url"]: 'identityTip/identityTip?type=service',
          ["grid[2].tap"]: 'gridNavigateUrl',
          ["grid[3].tap"]: 'gridNavigateUrl',
          ["grid[4].tap"]: 'gridNavigateUrl',
        })
      } else if (type == "agent") {
        that.setData({
          ["grid[0].tap"]: 'gridNavigateUrl',
          ["grid[0].url"]: 'proxyCenter/proxyCenter?level=' + app.globalData.userInfo.level,
        })
      } else if (type == 'shop') {
        that.setData({
          ["grid[0].tap"]: 'gridNavigateUrl',
          ["grid[0].url"]: 'identityTip/identityTip?type=agent',
          ["grid[5].tap"]: 'gridNavigateUrl',
          ["grid[5].url"]: 'identityTip/identityTip?type=service',
        })
      } else if (type == "engineer" || type == "salesman") {
        that.setData({
          ["grid[0].tap"]: 'gridTip',
          ["grid[1].tap"]: 'gridTip',
          ["grid[3].tap"]: 'gridTip',
          ["grid[4].tap"]: 'gridTip',
        })
      }
    } else {
      var type = 'visit';
      that.setData({
        ["grid[0].tap"]: 'gridTip',
        ["grid[1].tap"]: 'gridTip',
        ["grid[5].tap"]: 'gridTip',

        ["grid[2].tap"]: 'gridTip',
        ["grid[3].tap"]: 'gridTip',
        ["grid[4].tap"]: 'gridTip',
      })
    }
  },
  gridNavigateUrl: function (e) {
    var url = e.currentTarget.dataset.url;
    wx.navigateTo({
      url: "../../pages/" + url
    })
  },
  gridTip: function (e) {
    var that = this;
    var index = e.currentTarget.id;
    if (app.globalData.userInfo !== null && app.globalData.userInfo.type !== null) {
      that.identityType();
      var type = app.globalData.userInfo.type;
      switch (type) {
        case 'agent': {
          break;
        }
        case 'shop': {
          break;
        }
        case 'engineer': {
          this.modal("您已是维护人员，暂不能申请代理或商家")
          break;
        }
        case 'salesman': {
          this.modal("您已是维护人员，暂不能申请代理或商家")
          break;
        }
        default: break;
      }
    } else {
      wx.showModal({
        title: '提示',
        content: '您还未进行登录，小程序内的某些功能将无法正常使用，请问是否去登录？',
        success(res) {
          if (res.confirm) {
            that.setData({
              isHide: true
            });
          } else if (res.cancel) {
            that.setData({
              islogin: false
            });
            app.globalData.islogin = false;
          }
        }
      })
    }


  },
  // 点击授权
  bindGetUserInfo: function (e) {
    if (e.detail.userInfo) {
      //用户按了允许授权按钮
      var that = this;
      //授权成功后,通过改变 isHide 的值，让实现页面显示出来，把授权页面隐藏起来
      that.setData({
        isHide: false,
        islogin: true
      });
      app.globalData.islogin = true;
      app.registered(e.detail.userInfo)
      this.onLoad()
    } else {//用户按了拒绝按钮
      wx.showModal({
        title: '警告',
        content: '您点击了拒绝授权，将无法正常使用小程序，请授权之后再进入!',
        showCancel: false,
        confirmText: '返回',
        success: function (res) {
          // 用户没有授权成功，不需要改变 isHide 的值
          if (res.confirm) {
            console.log('用户点击了“返回授权”');
          }
        }
      });
    }
  },
  /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
  onPullDownRefresh: function () {
    this.onLoad();
  },
  onUnload() {
    clearTimeout(this.timer)
  }

})
